// import { baseUrl } from './request/doRequest';
import Taro from '@tarojs/taro'
import md5 from 'blueimp-md5'
import authority from './authority'
import { uploadToken } from '../api/uploadToken'

async function getToken() {
  // eslint-disable-next-line
  const name = md5(new Date().getTime()) + '.png' // todo
  const {
    accessid,
    callback,
    dir,
    host,
    policy,
    signature
  } = await uploadToken()
  const fd = {
    key: `${dir}${name}`,
    OSSAccessKeyId: accessid,
    policy,
    Signature: signature,
    callback
  }
  return { fd, host }
}

async function toUpload(filePath) {
  const { token } = authority.get() || {}
  const { fd, host } = await getToken()

  const Authorization = token ? `Bearer ${token}` : ''

  return new Promise((resolve, reject) => {
    Taro.showLoading({ title: '上传中' })
    Taro.uploadFile({
      url: host,
      filePath,
      name: 'file',
      formData: fd,
      header: {
        Authorization
      },
      success(res) {
        // todo
        if (res.statusCode === 200) {
          resolve(res.data)
          Taro.hideLoading()
        } else {
        }
      },
      fail(e) {
        reject(e)
        Taro.hideLoading()
      }
    })
  })
}

export function singleUpload() {
  return new Promise((resolve, reject) => {
    Taro.chooseImage({
      count: 1,
      success: ({ tempFilePaths }) => {
        const [filePath] = tempFilePaths
        toUpload(filePath)
          .then(resolve)
          .catch(reject)
      },
      fail(e) {
        reject(e)
      }
    })
  })
}
